package com.hoshiicloud.shxping.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hoshiicloud.common.constant.OrderInfoServiceStatusEnum;
import com.hoshiicloud.common.constant.refund.RefundOrderStatusEnum;
import com.hoshiicloud.common.constant.refund.RefundServiceTypeEnum;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.saleorder.entity.Consultations;
import com.hoshiicloud.saleorder.entity.OrderInfo;
import com.hoshiicloud.saleorder.entity.RefundOrder;
import com.hoshiicloud.saleorder.param.OrderInfoUpdateParam;
import com.hoshiicloud.saleorder.param.refund.RefundOrderCancelParam;
import com.hoshiicloud.shxping.dto.MemberDto;
import com.hoshiicloud.shxping.feign.IUserFeignService;
import com.hoshiicloud.shxping.feign.OrderFeignService;
import com.hoshiicloud.shxping.service.ShxpRefundOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;

/**
 * @author qry
 * @date 2019/9/4 14:42
 */
@Slf4j
@Service
public class ShxpRefundOrderServiceImpl implements ShxpRefundOrderService {
    @Resource
    private OrderFeignService orderFeignService;
    @Resource
    private IUserFeignService userFeignService;

    @Override
    public Boolean refundCancel(RefundOrderCancelParam param) {
        Response<RefundOrder> refundOrderRs = orderFeignService.getRefundOrderById(param.getRefundId());
        if (null == refundOrderRs || refundOrderRs.getCode() != 200 || null == refundOrderRs.getData()) {
            throw new ServiceException("获取退款单信息失败");
        }
        RefundOrder ro = refundOrderRs.getData();
        Response<MemberDto> memberRs = userFeignService.getMemberById(ro.getUserId());
        if (null == memberRs || memberRs.getCode() != 200 || null == memberRs.getData()) {
            throw new ServiceException("获取下单消费者失败");
        }

        Map<String,Object> map = new HashMap<>();
        map.put("avatar",memberRs.getData().getAvatar());
        map.put("nickName",memberRs.getData().getNickName());
        map.put("realName",memberRs.getData().getRealName());
        map.put("title","买家取消了退款申请");
        map.put("remark",null == param.getCancelReason() ? "" :param.getCancelReason());
        map.put("userType",0);

        Consultations consultations = new Consultations();
        consultations.setSubId(ro.getSubId());
        consultations.setRefundId(param.getRefundId());
        consultations.setStatus(RefundOrderStatusEnum.REFUND_CANCEL.getCode());
        consultations.setRemark(JSONObject.toJSONString(map));
        Response<Consultations> consultationsRs = orderFeignService.saveConsultations(consultations);
        if (null == consultationsRs || consultationsRs.getCode() != 200 || null == consultationsRs.getData()) {
            throw new ServiceException("新增退款单协商历史失败");
        }

        //删除旧的 系统协商历史记录
        Response<Boolean> consultationsDeleteRs = orderFeignService.deletePhysicConsultations(param.getRefundId());
        if (null == consultationsDeleteRs || consultationsDeleteRs.getCode() != 200 || null == consultationsDeleteRs.getData()) {
            throw new ServiceException("删除退款单协商历史系统记录失败");
        }

        //新增 新系统协商历史记录
        Consultations consultations2 = setSysConsu(ro.getSubId(), param.getRefundId(),"退款已取消",
                "退款取消后您可以再次发起申请，有任何问题您也可以寻求好获云平台的帮助（客服电话：400-023-8666）");
        Response<Consultations> consultationsRs2 = orderFeignService.saveConsultations(consultations2);
        if (null == consultationsRs2 || consultationsRs2.getCode() != 200 || null == consultationsRs2.getData()) {
            throw new ServiceException("新增退款单协商历史失败");
        }

        // 修改退款单状态
        RefundOrder entity = new RefundOrder();
        entity.setId(param.getRefundId());
        entity.setStatus(RefundOrderStatusEnum.REFUND_CANCEL.getCode());
        Response<Boolean> rs = orderFeignService.updataRefundOrderById(entity);
        if (null == rs || rs.getCode() != 200) {
            throw new ServiceException(rs.getMsg());
        }

        //  判断  订单是否已发货 是否超过发货时间 七天  如果否 订单售后状态修改为 可以售后   如果是 订单售后状态修改为售后关闭
        int orderInfoServiceStatus = OrderInfoServiceStatusEnum.CAN_AFTER_SALE.getCode() ;
        if(ro.getServiceType() == RefundServiceTypeEnum.REFUND_RETURN_GOODS.getCode()){
            Response<OrderInfo> orderInfoRs = orderFeignService.getOrderInfoById(ro.getSubId());
            if (null == orderInfoRs || orderInfoRs.getCode() != 200 || null == orderInfoRs.getData()) {
                throw new ServiceException("获取子订单信息失败");
            }
            LocalDateTime receiveTime = orderInfoRs.getData().getReceivedTime();
            //获取售后过期时间
            LocalDateTime refundExpireTime = receiveTime.plus(7, ChronoUnit.DAYS);

            //当前时间与售后过期时间相差的描述
            long i= Duration.between(LocalDateTime.now(), refundExpireTime).getSeconds();
            if(i< 0){
                orderInfoServiceStatus = OrderInfoServiceStatusEnum.AFTER_THE_COMPLETION_OF.getCode();
            }
        }
        OrderInfoUpdateParam orderInfoParam = new OrderInfoUpdateParam();
        orderInfoParam.setId(ro.getSubId());
        orderInfoParam.setServiceStatus(orderInfoServiceStatus);
        Response<Boolean> orderInfoUpdateRs =  orderFeignService.updateOrderInfoById(orderInfoParam);
        if (null == orderInfoUpdateRs || orderInfoUpdateRs.getCode() != 200 || null == orderInfoUpdateRs.getData()) {
            throw new ServiceException("更新子订单售后状态失败");
        }
        return true;
    }


    private Consultations setSysConsu(Long orderInfoId, Long refundId,String title,String msg) {
        Consultations consultations2 = new Consultations();
        consultations2.setSubId(orderInfoId);
        consultations2.setRefundId(refundId);
        consultations2.setStatus(RefundOrderStatusEnum.SYS_RECORD.getCode());
        Map<String,Object> map2 = new HashMap<>();
        map2.put("avatar","");
        map2.put("nickName","好获严选系统");
        map2.put("realName","");
        map2.put("title",title);
        map2.put("msg",msg);
        map2.put("userType",2);
        consultations2.setRemark(JSONObject.toJSONString(map2));
        return consultations2;
    }
}
